package com.eva.oss.api;

import com.eva.framework.common.api.BaseController;
import com.eva.framework.common.constants.ResponseStatus;
import com.eva.framework.common.exception.BusinessException;
import com.eva.framework.config.AppProperties;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;

@Tag(name = "本地文件访问")
@RestController
@RequestMapping("/resource/local")
public class LocalFileAccessController extends BaseController {

    @Resource
    private AppProperties appProperties;

    @GetMapping("/download")
    @Operation(summary = "下载")
    @Parameters({
            @Parameter(name = "path", description = "文件路径", required = true),
    })
    public void download (@RequestParam String path, HttpServletResponse response) throws IOException {
        // 读取文件
        File file = new File(appProperties.getLocalFileDirectory()
                .replace("~", new File("").getCanonicalPath()) + File.separator + path);
        if (!file.exists() || !file.isFile()) {
            throw new BusinessException(ResponseStatus.LOCAL_FILE_NOT_EXISTS);
        }
        // 获取文件字节流
        ByteArrayOutputStream os = this.getByteArrayOutputStream(Files.newInputStream(file.toPath()));
        // 下载
        this.downloadByteArray(file.getName(), os, response);
    }
}
